package com.jiangwz.sort;

/**
 * 归并排序
 *
 * @author jiangwz
 * @create 2021/3/19.
 */
public class MergeSort extends BaseSort {

    public static void main(String[] args) {
        int[] arr = new int[]{9, 1, 3, 2, 5, 6, 8, 7};
        mergeSort(arr, 0, arr.length - 1, new int[arr.length]);
        print(arr);
    }


    /**
     * 0 7 / 2 = 3
     * 4 7 / 2 = 5
     * @param arr
     * @param left
     * @param right
     * @param temp
     */
    public static void mergeSort(int[] arr, int left, int right, int[] temp) {
        if (left < right) {
            int mid = (right + left) / 2;
            mergeSort(arr, left, mid, temp);
            mergeSort(arr, mid + 1, right, temp);
            merge(arr, left, mid, right, temp);
        }
    }

    /**
     * 合并方法
     * @param arr
     * @param left  左指针
     * @param mid   中指针
     * @param right  右指针
     * @param temp
     */
    public static void merge(int[] arr, int left, int mid, int right, int[] temp) {
        int l = left; // 左指针
        int r = mid + 1; // 右指针
        int k = 0; //临时数组的指针
        while (l <= mid && r <= right) {
            if (arr[l] <= arr[r]) {
                temp[k++] = arr[l++];
            } else {
                temp[k++] = arr[r++];
            }
        }
        while (l <= mid) temp[k++] = arr[l++];
        while (r <= right) temp[k++] = arr[r++];

        // 把temp数组的值赋值到arr上
        // 假如当前 left=4 right=7  而 temp数组的下标从0开始,所以需要以下计算
        int kk = 0;
        int li = left;
        while (li <= right) {
            arr[li++] = temp[kk++];
        }

    }
}
